#!/usr/bin/env bash

PYTHON_VERSION=3.8.2

function err() {
    >&2 echo -e "\033[0;31m[ERROR]\033[0m" $@
    exit 1
}

function info() {
    echo -e "\033[0;34m[INFO]\033[0m" $@
}

CWD=${PWD}
OLD_PATH=$PATH

trap "cd ${CWD} && export PATH=${OLD_PATH}" EXIT
trap "cd ${CWD} && export PATH=${OLD_PATH}" SIGINT

if [ ! -z "${VIRTUAL_ENV}" ]; then
    err "Already in a Python virtualenv"
fi

# choose the correct binaries
info "Setting \$PATH"
export PRGA_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." >/dev/null 2>&1 && pwd )"
export PATH=${PRGA_ROOT}/local/bin:$PATH
pushd $PRGA_ROOT

# find pyenv
info "Finding 'pyenv'"
if command -v pyenv 2>&1 >/dev/null; then
    info "Active 'pyenv' found"
elif [ ! -f pyenv/bin/pyenv ]; then
    err "'pyenv' not found. Please run envscr/install first"
    exit 1
else
    export PYENV_ROOT=${PWD}/pyenv
    export PATH=${PWD}/pyenv/bin:$PATH

    info "Activating local-installed pyenv"
    eval "$( pyenv init - )"
    info "Local-installed pyenv activated"
fi

# select Python version
if $( pyenv local ${PYTHON_VERSION} ); then
    info "Python ${PYTHON_VERSION} selected"
else
    err "Python ${PYTHON_VERSION} not installed. Please run envscr/install first"
    exit 1
fi

# Run with virtualenv
cd prga.py
info "Entering Python virtualenv ..."
PIPENV_VENV_IN_PROJECT=1 pipenv run $*
info "Leaving Python virtualenv ..."

# roll back to the old state
info "Reverting \$PATH"
export PATH=$OLD_PATH
popd

info "Thanks for using PRGA. We look forward to your next use :)"

# vim: set ft=sh:
